// 鉴权中间件
package middleware

import (
	"github.com/gin-gonic/gin"
	"im-v1/config"
	"im-v1/tool"
	"log"
	"net/http"
	"time"
)

// Token校验
func Authentic() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.PostForm("token")

		// 未获取到token
		if token == "" {
			c.String(http.StatusBadRequest, "request invalid")
			c.Abort()
			return
		}

		// 验证token
		claim, err := tool.ParseToken(token)
		if err != nil {
			log.Println("解析token出现错误：", err)
			c.String(http.StatusBadRequest, "request invalid")
			c.Abort()
			return
		}

		// 时间过期
		if time.Now().Unix() > claim.ExpiresAt {
			c.String(http.StatusBadRequest, "token is out of the time limit")
			c.Abort()
			return
		}

		// 存储token的信息
		c.Set(config.TokenId, claim.Id)
		c.Set(config.TokenMail, claim.Mailbox)
		c.Set(config.TokenNick, claim.Nickname)
		c.Next()
	}
}
